package com.zhq.blog.manage.domain.quartz;

import java.util.List;

import javax.annotation.PostConstruct;
import javax.transaction.Transactional;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.zhq.blog.core.domain.Context;
import com.zhq.blog.core.domain.game.GamePeriod;
import com.zhq.blog.core.domain.game.support.Cathectic;
import com.zhq.blog.core.domain.other.DetailsOfFunds;
import com.zhq.blog.core.domain.other.DetailsOfFunds.DetailType;
import com.zhq.blog.core.domain.other.InternalMessage;
import com.zhq.blog.core.domain.user.User;

@Component
public class InitOnSetUp {
	
	@Autowired
	private Context context;
	
	@PostConstruct
	public void init(){
		deleteNOtLettryAndGiveBackBet();
	}
	
	/**
	 * 删除掉所有未开奖的 同时并退还给玩家投注金币
	 *1、找到之前所有未开奖的期数 
	 *2、循环遍历所有期数 根据每一期的期数和游戏类型找到所有的投注
	 *3、循环遍历所有的投注 根据玩家ID返还投注、发送返还投注站内信、生成资金变动明细
	 *
	 */
	@Transactional
	public void deleteNOtLettryAndGiveBackBet(){
		List<GamePeriod> list = context.getGamePeriodRepository().find_all_not_lottery();
		if(CollectionUtils.isNotEmpty(list)){
			for(GamePeriod g:list){
				List<Cathectic> cathectics = context.getCathecticRepository().find_all_not_lottery_and_give_back_bet(g.getGameId(), g.getPeriod());
				if(CollectionUtils.isNotEmpty(cathectics)){
					for(Cathectic c:cathectics){
						User user = context.getUserRepository().findOne(c.getUserId());
						DetailsOfFunds dof = new DetailsOfFunds(
								user.getId(),DetailType.GIVE_BACK,user.getCoin(),
								user.getCoin()+c.getBetMoney(),c.getBetMoney(),
								context.getGameRepository().findOne(c.getGameId()).getName(),c.getGamePeriod(),c.getBetNumber());
						context.getDetailsOfFundsRepository().save(dof);
						//使用特殊用户发送返还投注站内信
						context.getInternalMessageRepository().save(new InternalMessage(10000, user.getId(), dof.getDescription()));
						user.setCoin(user.getCoin()+c.getBetMoney());
						context.getUserRepository().update_user_coin_for_winning_money(user.getId(), c.getBetMoney());
						context.getCathecticRepository().delete(c.getId());
					}
				}
				context.getGamePeriodRepository().delete(g.getId());
			}
		}
	}
	
}
